package com.zlz.m3u8download.util;

import com.baomidou.mybatisplus.core.toolkit.AES;
import net.logstash.logback.util.StringUtils;
import org.springframework.util.DigestUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Author: zhulinzhong
 * @Date: 2024/11/28
 */
public class FileUtil {

    public static boolean contains(String route, String filePath) {
        Path path = Paths.get(route + filePath);
        return Files.exists(path);
    }

    public static boolean save(String route, String filePath, byte[] data) throws IOException {
        Path path = Paths.get(route + filePath);
        // 获取文件所在目录的路径
        Path parentDir = path.getParent();
        if (parentDir != null) {
            // 创建目录（包括各级不存在的父目录）
            Files.createDirectories(parentDir);
        }
        // 创建文件，如果文件已存在则覆盖（可根据需求调整行为）
        Files.deleteIfExists(path);
        Files.createFile(path);
        Files.write(path, data);

        // 检查文件
        return Files.exists(path);
    }

    public static String genTimeFolder() {
        LocalDate now = LocalDate.now();
        // 定义格式化字符串的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        return now.format(formatter);
    }

    public static String buildUrl(String parentUrl, String url) {
        parentUrl = parentUrl.substring(0, parentUrl.lastIndexOf("/") + 1);
        if (M3u8FileUtil.isAbsolute(url)) {
            return url;
        }
        if (url.startsWith("/")) {
            url = url.substring(1);
        }
        for (String s : url.split("/")) {
            parentUrl = parentUrl.replace(s + "/", "");
        }
        // 获取开始的数组坐标
        return parentUrl + url;
    }

    public static String md5(byte[] bytes) {
        return DigestUtils.md5DigestAsHex(bytes);
    }

}
